package com.zju.DoctorGo.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zju.DoctorGo.dto.UserEditPasswordDTO;
import com.zju.DoctorGo.dto.UserUnregisterDTO;
import com.zju.DoctorGo.entity.Doctor;
import com.zju.DoctorGo.entity.Patient;
import com.zju.DoctorGo.entity.User;
import com.zju.DoctorGo.dto.UserLoginDTO;
import com.zju.DoctorGo.mapper.UserMapper;
import com.zju.DoctorGo.service.DoctorYellowPageService;
import com.zju.DoctorGo.service.PatientService;
import com.zju.DoctorGo.service.UserService;
import com.zju.DoctorGo.utils.EmailVerifyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private EmailVerifyUtils emailVerifyUtils;

    @Autowired
    private DoctorYellowPageService doctorService;

    @Autowired
    private PatientService patientService;
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        User u=baseMapper.getByUserName(userLoginDTO.getUserName());
        if(u==null){
            throw new RuntimeException("用户名不存在");
        }
        //先进行md5加密，再进行对比
        String password= DigestUtils.md5DigestAsHex(userLoginDTO.getUserPassword().getBytes());
        if(!password.equals(u.getUserPassword())){
            throw new RuntimeException("密码错误");
        }
        return u;
    }

    @Override
    public void editPassword(UserEditPasswordDTO userEditPasswordDTO) {
        //将密码用md5加密
        userEditPasswordDTO.setUserPassword(DigestUtils.md5DigestAsHex(userEditPasswordDTO.getUserPassword().getBytes()));
        userEditPasswordDTO.setNewPassword(DigestUtils.md5DigestAsHex(userEditPasswordDTO.getNewPassword().getBytes()));
        Integer row=baseMapper.updatePassword(userEditPasswordDTO);
        if(row==0){
            throw new RuntimeException("修改密码失败");
        }
    }

    @Override
    public void unregister(UserUnregisterDTO userUnregisterDTO){
        userUnregisterDTO.setUserPassword(DigestUtils.md5DigestAsHex(userUnregisterDTO.getUserPassword().getBytes()));
        Integer row=baseMapper.deleteByIdAndPassword(userUnregisterDTO);
        if(row==0)
            throw new RuntimeException("注销账号失败");
        // 根据用户类型删除关联记录
        if (userUnregisterDTO.getUserType() == 2) {
            doctorService.removeById(userUnregisterDTO.getUserId());
        } else if (userUnregisterDTO.getUserType() == 1) {
            patientService.removeById(userUnregisterDTO.getUserId());
        }
    }

    @Override
    public User getByUserName(String userName) {
        return baseMapper.getByUserName(userName);
    }

    @Override
    public Map<String, Object> getVerifyCode(String targetEmailBox) {
        String code = emailVerifyUtils.generateCode(6);
        emailVerifyUtils.sendEmail(targetEmailBox,code);
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, 5);
        String currentTime = sf.format(c.getTime());// 生成5分钟后时间，用户校验是否过期
        String hash =  DigestUtils.md5DigestAsHex(("ZJU" + "@" + currentTime + "@" + code).getBytes());//生成MD5值
        Map<String, Object> resultMap = new HashMap<>();	//返回的map
        resultMap.put("hash", hash);
        resultMap.put("tamp", currentTime);
        return resultMap;
    }

    @Override
    public void veryfyCode(Map<String, Object> requestMap, String code) {
        String requestHash = requestMap.get("hash").toString();
        String tamp = requestMap.get("tamp").toString();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");//当前时间
        Calendar c = Calendar.getInstance();
        String currentTime = sf.format(c.getTime());
        if (tamp.compareTo(currentTime) > 0) {
            String hash =  DigestUtils.md5DigestAsHex(("ZJU" + "@" + tamp + "@" + code).getBytes());//生成MD5值
            if (hash.equalsIgnoreCase(requestHash)){
                //校验成功
                return ;
            }else {
                //验证码不正确，校验失败
                throw new RuntimeException("验证码错误");
            }
        } else {
            // 超时
            throw new RuntimeException( "验证码已失效");
        }
    }

    @Override
    public void register(User user) {
        User u=baseMapper.getByUserName(user.getUserName());
        if(u!=null)
            throw new RuntimeException("用户名已存在");
        user.setUserPassword(DigestUtils.md5DigestAsHex(user.getUserPassword().getBytes()));
        baseMapper.insert(user);

        if (user.getUserType() == 2) {
            Doctor doctor = new Doctor();
            doctor.setUserId(user.getUserId());
            doctor.setName(user.getUserName());
            doctor.setAge(-1);
            doctor.setGender(-1);
            doctor.setSpeciality("-1");
            doctorService.createDoctor(doctor);
        } else if (user.getUserType() == 1) {
            Patient patient = new Patient();
            patient.setUserId(user.getUserId());
            patient.setName(user.getUserName());
            patient.setAge(-1);
            patient.setGender(-1);
            patientService.createPatient(patient);
        }

    }
}
